package com.example.nettydemo.bio_2;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author juzhenxing
 * @date 2020/11/4
 * @description
 */
@Slf4j
public class TimeClient {

    public static void main(String[] args) {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            socket = new Socket("127.0.0.1", port);
            while (true) {
                // "abc\n"
                String sendMsg = "abc\n";
                log.info("request: [{}]", sendMsg);
                out = new PrintWriter(socket.getOutputStream(), true);
                out.print(sendMsg);
                // 需要!!!
                out.flush();

                // 只能读取一次, 重复读取报java.net.SocketException: Software caused connection abort: recv failed
                // 在服务端/客户端单方面关闭连接的情况下,另一方依然以为 tcp连接仍然建立,试图读取对方的响应数据,导致出现 Software caused connection abort: recv failed的异常
                //  socket.getInputStream().available()
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String resp = in.readLine();
                log.info("response: [{}]", resp);

                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}
